package utilitario;

import java.awt.Color;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.JTextField;

public class JTextFieldChanged extends JTextField {

	private static final long serialVersionUID = 1L;
    JTextField textoBorde;
    int numCar;

    public JTextFieldChanged(int parNumCar) {

        super.setDisabledTextColor(Color.BLACK);
        textoBorde = new JTextField();
        this.numCar = parNumCar;

        super.addPropertyChangeListener(new PropertyChangeListener() {
            @Override
            public void propertyChange(PropertyChangeEvent evt) {
                JTextField control = (JTextField) evt.getSource();
                if (control.isEnabled()) {

                    control.setBorder(textoBorde.getBorder());
//                    control.setBackground(Color.WHITE);
                    control.setOpaque(true);
                    
                }
                else if (!control.isEnabled()) {

                    control.setBorder(javax.swing.BorderFactory.createEtchedBorder());
                    control.setBackground(textoBorde.getBackground());
                    control.setOpaque(false);
                    
                }
            }
        });

        super.addFocusListener(new FocusListener() {
            @Override
            public void focusGained(FocusEvent e) {

                JTextField control = (JTextField) e.getSource();
                control.setSelectionStart(0);
                control.setSelectionEnd(control.getText().trim().length());
                control.setBackground(Color.YELLOW);
                control.setOpaque(true);

            }

            @Override
            public void focusLost(FocusEvent e) {

                JTextField control = (JTextField) e.getSource();
                control.setBackground(Color.WHITE);
                control.setOpaque(true);

            }
        });

        super.addKeyListener(new KeyAdapter() {
            @Override
            public void keyTyped(KeyEvent e) {

                JTextField control = (JTextField) e.getSource();
                if (control.getText().trim().length() >= numCar
                        || (e.getKeyCode() == KeyEvent.VK_SPACE && control.getText().trim().length() >= numCar)) {

//                    System.out.println("ttecto  " + control.getText().trim() + this.getClass().getName());
                    control.setText(control.getText().trim().substring(0, numCar));
                    e.consume();

                }
            }//Fin de metodo keyTyped
        });
    }//Fin de Constructor
}//Fin de Clase Principal
